local Msg = require("core.Msg")
local InnerMsg = require("core.InnerMsg")
local ObjHuman = require("core.ObjHuman")
local Util = require("common.Util")
local Config = require("Config")
local Lang = require("common.Lang")
local LuaMongo = _G.lua_mongo
local DB = require("common.DB")
local RoleDBLogic = require("role.RoleDBLogic")
local CombatLogic = require("combat.CombatLogic")
local CombatPosLogic = require("combat.CombatPosLogic")
local CombatDefine = require("combat.CombatDefine")
local UnionWarDBLogic = require("union.UnionWarDBLogic")
local UnionWarMiddleLogic = require("union.UnionWarMiddleLogic")
local HeroGrid = require("hero.HeroGrid")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local Broadcast = require("broadcast.Broadcast")
local RoleDefine = require("role.RoleDefine")
local UnionDBLogic = require("union.UnionDBLogic")
local RoleLogic = require("role.RoleLogic")
local MailManager = require("mail.MailManager")
local BattleLogic = require("battle.BattleLogic")
local MailDefine = require("mail.MailIdDefine")
local MailExcel = require("excel.mail").mail
local MonsterOutExcel = require("excel.monster").monsterOut
local UnionWarExcel = require("excel.unionWar")
local RobotExcel = UnionWarExcel.robot
local DefineConf = UnionWarExcel.define[1]
local LvExcel = UnionWarExcel.lv
local RankExcel = UnionWarExcel.rank
local RoleSystemLogic = require("roleSystem.RoleSystemLogic")
local RoleSystemDefine = require("roleSystem.RoleSystemDefine")
local BillboardDB = require("billboard.BillboardDB")
local BillboardDefine = require("billboard.BillboardDefine")
local Broadcast = require("broadcast.Broadcast")
local Timer = require("core.Timer")
local MiddleConnect = require("middle.MiddleConnect")

--活动阶段
WDAY = {[1] = 1,[3] = 1,[5] = 1}
--获取公会战阶段
HOUR1 = {5,8}  --确认
HOUR2 = {8,12}  --匹配
HOUR3 = {12,20} --战斗
HOUR4 = {20,24} --结算

STATE0 = 0 --非活动阶段
STATE1 = 1 --确认
STATE2 = 2 --匹配
STATE3 = 3 --战斗
STATE4 = 4 --结算

UNION_STATE1 = 1 --匹配成功
UNION_STATE2 = 2 --确认不成功
UNION_STATE3 = 3 --匹配不成功

UNION_LV = 2 -- 公会等级条件
UNION_HUOYUE = 5 --功会活跃人数条件
HUOYUE_TIME = 86400
UNION_FEIXU_CNT = 5  -- 废墟可挑战次数

local function getLocalUnionWarData(localData,unionUuid)
    localData[unionUuid] = localData[unionUuid]  or {member = {},memberCnt = 0,star = 0,cnt = 0,exp = 0,lv = 0,rank = {}}
    return localData[unionUuid]
end

local function getLocalMemberData(unionWarData,uuid)
    unionWarData.member[uuid] = unionWarData.member[uuid] or {name = "",cnt = 0,shop = {{},{}},chengjiu = {{},{}}}
    return unionWarData.member[uuid]
end 

local function getUnionWarRankRewardID(rank)
    for k, v in ipairs(RankExcel) do
        if v.minRank <= rank and rank <= v.maxRank then
            return k
        end
    end
    return 0
end

local function getUnionWarData(human,memberData)
    if not human.db.unionWarData then
        human.db.unionWarData = {}
        human.db.unionWarData.shop = Util.copyTable(memberData.shop)
        human.db.unionWarData.upShopTime = memberData.upShopTime
        human.db.unionWarData.chengjiu = Util.copyTable(memberData.chengjiu)
        human.db.unionWarData.cnt = memberData.cnt
    end
    local now = os.time()
    if not human.db.unionWarData.upShopTime or human.db.unionWarData.upShopTime < now then
        human.db.unionWarData.upShopTime = Util.getWeekStartTime(now) + 86400 * 7 
        human.db.unionWarData.shop[1] = {}
    end
    return human.db.unionWarData
end

function fontFakeObj(objList)
    local fakeList = {}

    for i = 1, CombatDefine.COMBAT_HERO_CNT do
        local obj = objList[i]
        if obj then
            fakeList[i] = {}
            fakeList[i] = Util.copyTable(obj)
            local fake = fakeList[i]
            fake.beSkillList = nil
            fake.skillList = nil
            fake.beSkillListTemp = nil
            fake.attrs = nil
            fake.attrs2 = {}
            fake.attrs2[RoleDefine.HP] = obj.attrs[RoleDefine.HP]
            fake.attrs2[RoleDefine.DEF] = obj.attrs[RoleDefine.DEF]
            fake.attrs2[RoleDefine.ATK] = obj.attrs[RoleDefine.ATK]
            fake.attrs2[RoleDefine.SPEED] = obj.attrs[RoleDefine.SPEED]
            fake.attrs2[RoleDefine.ATK_RATE] = obj.attrs[RoleDefine.SPEED_RATE]
            fake.attrs2[RoleDefine.DEF_RATE] = obj.attrs[RoleDefine.SPEED_RATE]
            fake.attrs2[RoleDefine.HP_RATE] = obj.attrs[RoleDefine.SPEED_RATE]
            fake.attrs2[RoleDefine.SPEED_RATE] = obj.attrs[RoleDefine.SPEED_RATE]

   --         fake.attrsting = ""
    --        for k,v in pairs(obj.attrs) do
    --            fake.attrsting = fake.attrsting .. "|" .. k.. "," .. v
     --       end
        end
    end
    return fakeList
end

local function getData(data)
    if data.lv < UNION_LV then return end
    local unionData = {member = {}}
    local len = 0
    local huoyueCnt = 0
    local sortList = {}
    local localData = UnionWarDBLogic.getLocalData()
    local unionUuid = data._id    
    local now = os.time()

    local d = os.date("*t",now)
    d.hour = HOUR4[1]
    d.min = 0
    d.sec = 0 
    local boxEndTime = os.time(d) + 24 * 3600 

    local donateTime = Util.getDayStartTime(os.time())
    donateTime = donateTime - HUOYUE_TIME
    localData[unionUuid] = localData[unionUuid]  or {member = {},memberCnt = 0,star = 0,cnt = 0,exp = 0,lv = 0,rank = {}}
    localData[unionUuid].rank = {}
    if localData[unionUuid].box and localData[unionUuid].box.endTime and localData[unionUuid].box.endTime < now then  
        localData[unionUuid].isWin = nil
        localData[unionUuid].isMatch = nil
    end
    for k,v in pairs(data.member) do
        local db = RoleDBLogic.getDb(k)
        if db then
            if db.lastLoginTime and db.lastLoginTime >= donateTime then
                huoyueCnt = huoyueCnt + 1
            end
            local objList, helpList, rolebase,formation, jiban = CombatLogic.getHumanObjList({db = db},CombatDefine.COMBAT_TYPE3)
            if rolebase.zhandouli > 0 then
                len = len + 1
                local battleMonsterOutID = BattleLogic.getCombatMonsterOutID({db = db}, CombatDefine.DEFEND_SIDE)
                if not battleMonsterOutID then
                    battleMonsterOutID = 10001
                end
                unionData.member[k] = {objList = objList,helpList = helpList,formation = formation, jiban = jiban , rolebase = rolebase,name = db.name ,attackStar = 0,defendStar = 3,defendCnt = 0,attackCnt = 0, jifen = 0,log = {},battleMonsterOutID = battleMonsterOutID} --
                sortList[len] = {k,rolebase.zhandouli}
                localData[unionUuid].member[k] = localData[unionUuid].member[k] or {name = db.name,cnt = 0,shop = {{},{}},chengjiu = {{},{}}}
                localData[unionUuid].member[k].join = 1
                localData[unionUuid].member[k].post = v.post
                localData[unionUuid].member[k].rolebase = rolebase 
                localData[unionUuid].member[k].boxTime = boxEndTime
            end
        end
    end

    if len == 0 or huoyueCnt < UNION_HUOYUE then
        return
    end

    for k, v in pairs(localData[unionUuid].member) do
        if not data.member[k] then
            localData[unionUuid].member[k] = nil
        end
    end

    table.sort(sortList,function(a,b)
        return a[2] > b[2]
    end)

    for k,v in ipairs(sortList) do
        unionData.member[v[1]].index = k
        localData[unionUuid].rank[k] = {v[1],0,0}
    end

    unionData.memberCnt = len
    unionData.unionUuid = data._id
    unionData.name = data.name
    unionData.bannerID = data.bannerID
    unionData.lv = data.lv
    unionData.zhandouli = data.zhandouli
    unionData.svrName = Config.SVR_NAME
    unionData.svrIndex = Config.SVR_INDEX
    unionData.rank = BillboardDB.getRank(BillboardDefine.TYPE_UNION,data._id) or 0

    localData[unionUuid].memberCnt = len
    localData[unionUuid].star = 0
    return unionData
end

--重置公会战数据（资格确认）
fileds = {unionUuid = 1,name = 1,bannerID = 1,lv = 1,zhandouli = 1,member = 1}
local  ToMidUnionList = nil
function refreshData()
    print("   refreshData  refreshData  refreshData")
    ToMidUnionList = {}
    LuaMongo.find(DB.db_union,nil,fileds)
    local msgRet = InnerMsg.lw.LW_UNION_WAR_ADD
    msgRet.list = {}
    local len = 0
    local unionList = {}
    local unionUuid
    while true do 
        local data = {}
        if not LuaMongo.next(data) then
            break
        end
        unionList[#unionList + 1] = data
    end
    for k,data in ipairs(unionList) do
        local unionData = getData(data)
        if unionData then
            unionUuid = unionData.unionUuid
            local toLen = #ToMidUnionList + 1
            ToMidUnionList[toLen] = {}
            ToMidUnionList[toLen].member = {}
            ToMidUnionList[toLen].unionUuid = unionUuid
            ToMidUnionList[toLen].member = Util.copyTable(unionData.member)
            unionData.member = {}
            len = len + 1
            msgRet.list[len] = unionData
        end
        if len >= 5 then
            InnerMsg.sendMsg(0, msgRet)
            Util.cleanTable(msgRet.list)            
            len = 0
        end
    end

    if len >= 1 then
        InnerMsg.sendMsg(0, msgRet)
    end    
    UnionWarDBLogic.updateDB()
    print("  Timer.addLater(1, sendUnionToMid)   Timer.addLater(1, sendUnionToMid)")
    Timer.addLater(1, sendUnionToMid)
end

local function getSurCnt(member) 
    local len = 0
    if not member then return len end
    for _ in pairs(member) do
        len = len + 1
    end
    return len 
end

function sendUnionToMid()
    print("  sendUnionToMid , sendUnionToMid   ,  sendUnionToMid")
    if ToMidUnionList and #ToMidUnionList > 0 then
        print("  sendUnionToMid  sendUnionToMid  sendUnionToMid", #ToMidUnionList)
        local data = ToMidUnionList[#ToMidUnionList]
        if data and data.unionUuid then
            local msgRet = InnerMsg.lw.LW_UNION_WAR_MEMBER
            msgRet.unionUuid = data.unionUuid
            msgRet.list = {}
            Util.cleanTable(msgRet.list)    
            local len = 0
            local sendUuid = {}
            if #ToMidUnionList == 1 and getSurCnt(data.member) <= 10 then
                data.isEnd = 1
            end
            local isSend = false
            msgRet.isEnd = data.isEnd or 0
            for k,v in pairs(data.member) do
                len = len + 1
                msgRet.list[len] = {k,v}
                sendUuid[k] = 1
                if len >= 10 then
                   -- Util.printTable(msgRet)
                    InnerMsg.sendMsg(0, msgRet)
                    Util.cleanTable(msgRet.list)                   
                    isSend = true
                    break
                end
            end

            if not isSend then
          --      Util.printTable(msgRet)
                InnerMsg.sendMsg(0, msgRet)
                Util.cleanTable(msgRet.list)       
            end

            local surLen = 0
            for uuid in pairs(data.member) do
                if sendUuid[uuid] then
                    data.member[uuid] = nil
                else
                    surLen = surLen + 1 
                end               
            end
            print("  surLen  surLen  ", surLen)
            if surLen == 0 then
                ToMidUnionList[#ToMidUnionList] = nil
                print("  del   ToMidUnionList  !", #ToMidUnionList)
            end

            if #ToMidUnionList > 0 then
                Timer.addLater(1, sendUnionToMid)
            else
                ToMidUnionList = nil
            end           
        end
    end
end


-- 匹配完成  各个单服 将匹配上的 公会标记  用于红点
function middleUnionMatchFinish(msg)
    local localData = UnionWarDBLogic.getLocalData()
    for unionUuid in pairs(msg.list) do
        if localData[unionUuid] then
            localData[unionUuid].isMatch = true
            localData[unionUuid].matchTime = os.time()
        end
    end
end

function getState()
    local now = os.time()
    local d = os.date("*t",now)
    local wday = d.wday
    local h = d.hour
    -- 周一 周三 周五   公会战
    if WDAY[wday - 1] then
        if h >= HOUR1[1] and h < HOUR1[2] then
            return STATE1
        elseif h >= HOUR2[1] and h < HOUR2[2] then 
            return STATE2
        elseif h >= HOUR3[1] and h < HOUR3[2] then 
            return STATE3
        elseif h >= HOUR4[1] and h < HOUR4[2] then 
            return STATE4
        end
    end

    return STATE0
end

function getEndTime(actState)
    local now = os.time()
    local d = os.date("*t",now)
    if actState == STATE0 then       
        local wday = d.wday
        if wday < 6 then
            d.hour = HOUR2[2]
            local checkTime = os.time(d)
            return checkTime + 24 * 60 * 60 - now
        elseif wday == 6 then
            if actState < STATE3 then
                d.hour = HOUR2[2]
            else
                d.hour = HOUR3[2]
            end      
            d.min = 0
            d.sec = 0
            local checkTime = os.time(d)
            return checkTime - now
        else
            local Monday = Util.getWeekStartTime()
            return Monday + 24 * 60 * 60 * 7 + HOUR2[2] * 3600 - now
        end
    else
        if actState < STATE3 then
            d.hour = HOUR2[2]
        else
            d.hour = HOUR3[2]
        end      
        d.min = 0
        d.sec = 0
        local checkTime = os.time(d)
        return checkTime - now
    end
end

function getWarTime(human)
    local msgRet = Msg.gc.GC_UNION_WAR_TIME
    if MiddleConnect.IS_MIDDLE_CONNECT then
        local actState = getState()
        msgRet.actState = actState
        msgRet.time = getEndTime(actState)
        Msg.send(msgRet,human.fd)
    else
        msgRet.actState = 0
        msgRet.time = 0
        Msg.send(msgRet,human.fd)
    end
    
end

local function getChengjiuExcel(type)
    if type == 1 then
        return UnionWarExcel.chengjiu1
    else
        return UnionWarExcel.chengjiu2
    end
end

local function isDotChengjiu(human,localData,unionWarData,memberData,type)
    local ChengjiuExcel = getChengjiuExcel(type)
    if not memberData then
        --未参与公会战
        return
    end
    local getList,cnt
    local humanData = getUnionWarData(human,memberData)
    if type == 1 then
        cnt = humanData.cnt
        getList = humanData.chengjiu[1]
    else
        cnt = unionWarData.cnt
        getList = humanData.chengjiu[2]
    end
    for k, v in ipairs(ChengjiuExcel) do
        if not getList[k] and v.cnt <= cnt then
            return true
        end
    end
end

local function sendState(human,actState,unionState)
    local msgRet = Msg.gc.GC_UNION_WAR_STATE
    msgRet.actState = actState
    msgRet.unionState = unionState 
    msgRet.winState = 0
    msgRet.cjDot = 0
    msgRet.zgDot = 0
    msgRet.shopDot = 0
    msgRet.fightDot = 0
    msgRet.pipeiDot = 0
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData =  getLocalUnionWarData(localData,human.db.unionUuid)
    local memberData = getLocalMemberData(unionWarData,human.db._id)

    if unionWarData and memberData and isDotChengjiu(human,localData,unionWarData,memberData,1) or isDotChengjiu(human,localData,unionWarData,memberData,2) then
        msgRet.cjDot = 1
    end

    if unionWarData and isDotByBox(human, unionWarData) then
        msgRet.zgDot = 1
    end

    if unionWarData and isDotByShop(human, unionWarData) then
        msgRet.shopDot = 1
    end

    if unionWarData and isDotByCnt(human, unionWarData) then
        msgRet.fightDot = 1
    end

    if unionWarData and isDotByPiPei(human, unionWarData) then
        msgRet.pipeiDot = 1
    end

    if actState == STATE4 and unionState == UNION_STATE1 then        
        msgRet.winState = unionWarData.isWin and unionWarData.isWin or 0
    end
    Msg.send(msgRet,human.fd)
end

--请求：查询状态
--返回：状态，攻守双方成员
local function fontUnionWarTeam(net,data)
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData = getLocalUnionWarData(localData,data.unionUuid)
    local rankData = unionWarData.rank
    local temp = {}
    for i = 1,3 do
        if rankData[i] then
            temp[rankData[i][1]] = i
        else
            break
        end
    end

    net.unionUuid = data.unionUuid
    net.name = data.name
    net.svrName = data.svrName or ""
    net.bannerID = data.bannerID
    net.star = data.star
    local len = 0
    for k,v in pairs(data.member) do
        len = len + 1
        net.list[len].index = v.index
        net.list[len].uuid = v.uuid
        net.list[len].name = v.name
        net.list[len].star = v.star
        net.list[len].zhandouli = v.zhandouli
        net.list[len].rank = temp[v.uuid] or 0
        local pos = RobotExcel[v.index].pos
        net.list[len].x = pos[1]
        net.list[len].y = pos[2]
    end
    net.list[0] = len
end

local function fontSimpleRank(net,unionUuid)
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData = getLocalUnionWarData(localData,unionUuid)
    local memberList = unionWarData.member
    local len = 0
    local fields = {name = 1}
    local db
    for k,v in ipairs(unionWarData.rank) do
        len = len + 1
        net[len].rank = k
        db = RoleDBLogic.getDb(v[1], fields)
        net[len].name =  db and db.name or memberList[v[1]].name

        if len >= 3 then
            break
        end
    end
    net[0] = len
end

function onLogin(human)

end

function query(human,msg, actState)
    local msgRet = Msg.gc.GC_UNION_WAR_QUERY
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData = getLocalUnionWarData(localData,human.db.unionUuid)
    
    fontUnionWarTeam(msgRet.attacker,msg.attacker)
    fontUnionWarTeam(msgRet.defender,msg.defender)
    fontSimpleRank(msgRet.threeRank,msg.attacker.unionUuid)

    local now = os.time()
    local d = os.date("*t",now)
    d.hour = HOUR3[2]
    --[[
if actState == STATE2 then
        d.hour = HOUR2[2]
    else
        d.hour = HOUR3[2]
    end
    ]]
    
    d.min = 0
    d.sec = 0
    local checkTime = os.time(d)
    msgRet.leftTime = checkTime - now
    msgRet.cnt = msg.cnt
    msgRet.maxCnt = DefineConf.cnt
 --   Msg.trace(msgRet)
    Msg.send(msgRet,human.fd)
end

function CGQuery(human)
    
end

function WLQuery(human,msg)
    local actState = getState()
    sendState(human,actState,msg.state)
    if msg.state == UNION_STATE1 then
        query(human,msg, actState)
    end
end

-- 客户端 最多请求三次
-- 用于给 客户端  给予 停留在公会战界面  倒计时结束 公会战结果 查询更新
function CGEndQuery(human)
    local msgRet = Msg.gc.GC_UNION_WAR_END_STATE_QUERY
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData =  getLocalUnionWarData(localData,human.db.unionUuid)
    msgRet.winState = unionWarData.isWin and unionWarData.isWin or 0
    Msg.send(msgRet,human.fd)
end

local function fontBufferNet(msgRet, lv)   
    msgRet.maxBuff = #UnionWarExcel.buff
    local config = UnionWarExcel.buff[lv]

    msgRet.nowAttr[0] = 0
    msgRet.nextAttr[0] = 0

    if config then
        for k, v in ipairs(config.attr) do
            local net = msgRet.nowAttr[k]
            net.key = v[1]
            net.value = v[2]
        end
        msgRet.nowAttr[0] = #config.attr   
    end
    
    
    if lv + 1 <= msgRet.maxBuff then
        local nextConfig = UnionWarExcel.buff[lv + 1]
        for k, v in ipairs(nextConfig.attr) do
            local net = msgRet.nextAttr[k]
            net.key = v[1]
            net.value = v[2]
        end
        msgRet.nextAttr[0] = #nextConfig.attr  
    end
    
end

-- BUF 请求
function CGBuffQuery(human)
    local msgRet = Msg.gc.GC_UNION_WAR_BUFF
    msgRet.buffLv = 0
    fontBufferNet(msgRet, 0)
    if human then
        Msg.send(msgRet,human.fd)
    end

    local actState = getState()
    if actState > STATE1 then
        local msgRet =  InnerMsg.lw.LW_UNION_WAR_BUFF_QUERY
        msgRet.uuid = human.db._id
        msgRet.unionUuid = human.db.unionUuid

        InnerMsg.sendMsg(0, msgRet)
    end
end

function WLBuffQuery(human, msg)
    local msgRet = Msg.gc.GC_UNION_WAR_BUFF
    msgRet.buffLv = msg.buffLv
    fontBufferNet(msgRet, msg.buffLv)
    if human and human.fd then
        Msg.send(msgRet,human.fd)
    else
        local localData = UnionWarDBLogic.getLocalData()
        local unionWarData = getLocalUnionWarData(localData, msg.unionUuid)
        if not unionWarData  or not unionWarData.member then return end 
        for uuid,_ in pairs(unionWarData.member) do
            local human = ObjHuman.onlineUuid[uuid]
            if human and human.fd then
                Msg.send(msgRet,human.fd)
            end           
        end
    end
end

--请求：公会成员信息
--返回：公会成员信息
function CGInfo(human,unionUuid,targetUuid)
    local msgRet =  InnerMsg.lw.LW_UNION_WAR_INFO
    msgRet.uuid = human.db._id
    msgRet.attackUnionUuid = human.db.unionUuid
    msgRet.unionUuid = unionUuid
    msgRet.targetUuid = targetUuid
    InnerMsg.sendMsg(0, msgRet)
end

-- 封装 英雄
local function fontHeroList(net,data)
    local len = 0
    local monsterOutID = data.monsterOutID
    if monsterOutID then
        for k,v in ipairs(MonsterOutExcel[monsterOutID].member) do
            if v[1] > 0 then
                len = len + 1
                HeroGrid.makeHeroSimpleByMonsterID(net[len],v[1],{lv = v[2]})
            end
        end
    else
        for i = 1,CombatDefine.COMBAT_HERO_CNT do
            local obj = data.objList[i]
            if obj then
                len = len + 1
                HeroGrid.makeHeroSimpleByID(net[len],obj.id, obj.bagIndex,{lv = obj.lv,star = obj.star})
            end
        end
    end
    net[0] = len
end

function getDiff(robotConf,diff,monsterOutID, isFeixu)
    if isFeixu then
        diff = 3
        return robotConf.rate[diff],0,robotConf.jifen2
    else
        return robotConf.rate[diff],robotConf.star[diff],robotConf.jifen1[diff]
    end
   
end
-- 玩家信息
function WLInfo(human,msg)
    local msgRet = Msg.gc.GC_UNION_WAR_INFO
    local target = msg.target

    msgRet.cnt = msg.cnt
    msgRet.maxCnt = DefineConf.cnt
    msgRet.unionUuid = msg.unionUuid
    msgRet.uuid = target.uuid
    msgRet.index = msg.index
    msgRet.star = target.defendStar
    msgRet.zhandouli = target.zhandouli
    msgRet.defendCnt = target.defendCnt
    msgRet.canFight = msg.canFight
    msgRet.feixuCnt = target.loseBuff
    local len = 0

    local monsterOutID = target.monsterOutID
    if monsterOutID then
        msgRet.isRobot = 1
    else
        msgRet.isRobot = 0
    end
    local robotConf = RobotExcel[target.index]
    local diffList = robotConf.diff
    local isFeixu = target.defendStar <= 0
    if isFeixu then
        diffList = {3}
    end
    for k,v in ipairs(diffList) do
        len = len + 1
        local net = msgRet.diffList[len]
        net.diff = v
        net.rate,net.star,net.jifen = getDiff(robotConf,k,monsterOutID)
        local len1 = 0
        for k1,v1 in ipairs(robotConf.item[v]) do
            len1 = len1 + 1
            Grid.makeItem(net.item[len1], v1[1], v1[2])
        end
        net.item[0] = len1

    end
    msgRet.diffList[0] = len
  --  Util.printTable(target)
    fontHeroList(msgRet.list,target)
    Msg.send(msgRet,human.fd)
end

--请求：匹配列表
--返回：匹配列表

function CGMatch(human)
    local msgRet =  InnerMsg.lw.LW_UNION_WAR_MATCH
    msgRet.uuid = human.db._id
    msgRet.unionUuid = human.db.unionUuid
    InnerMsg.sendMsg(0, msgRet)
end

function WLMatch(human,msg)
    local msgRet = Msg.gc.GC_UNION_WAR_MATCH
    local len = 0
    for k,v in ipairs(msg.list) do
        len = len + 1
        local net = msgRet.list[len]
        net.nameLeft = v[1][1]
        net.rankLeft = v[1][3] or 0
        net.nameRight = v[2][1]
        net.rankRight = v[2][3] or 0
        net.svrNameLeft = v[3][3] 
        net.svrNameRight = v[3][4]
        if len >= 60 then
            break
        end  
    end
    msgRet.list[0] = len
    Msg.send(msgRet,human.fd)

    if human.db.unionUuid then
        local localData = UnionWarDBLogic.getLocalData()
        local unionWarData =  getLocalUnionWarData(localData,human.db.unionUuid)
        if unionWarData then 
            local memberData = getLocalMemberData(unionWarData,human.db._id)
            local humanData = getUnionWarData(human,memberData)
        
            local actState = getState()
        
            if actState >= STATE2 and not Util.isSameDay(humanData.pipeiLook) then
                humanData.pipeiLook = os.time()
                RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_1006)
            end        
        end
    end
end

--请求：日志
--返回：日志
function CGAtkLog(human, type)
    local msgRet =  InnerMsg.lw.LW_UNION_WAR_ATKLOG
    msgRet.uuid = human.db._id
    msgRet.type = type
    msgRet.unionUuid = human.db.unionUuid
    InnerMsg.sendMsg(0, msgRet)  
end

function WLAtkLog(human, msg)
    local msgRet = Msg.gc.GC_UNION_WAR_ATKLOG
    msgRet.type = msg.type
    local len = 0
    for k,v in ipairs(msg.list) do
        len = len + 1
        local net = msgRet.list[len]
        net.upTime = v[1]
        net.ret = v[2] and 1 or 0
        net.name = v[3]
        net.defName = v[4]
        net.star = v[5]
        net.jifen = v[6]
        net.unionUuid = v[7]
        net.atkUnionStar = v[8] or 0
        net.buffLv = v[9] and v[9] or 0
    end
    msgRet.list[0] = len
 --   Msg.trace(msgRet)
    Msg.send(msgRet,human.fd)
end

--请求 防守日志
--返回 防守日志
function CGDefLog(human,uuid, unionUuid)
    local msgRet = InnerMsg.lw.LW_UNION_WAR_DEFLOG
    msgRet.uuid = human.db._id
    msgRet.unionUuid = human.db.unionUuid
    msgRet.defendUuid = uuid
    msgRet.defendUnion = unionUuid
    InnerMsg.sendMsg(0, msgRet)
end

function WLDefLog(human,msg)
    local msgRet = Msg.gc.GC_UNION_WAR_DEFLOG
    msgRet.zhandouli = msg.defender.zhandouli
    fontHeroList(msgRet.heroList,msg.defender)
    local len = 0
    for k,v in ipairs(msg.list) do
        len = len + 1
        local net = msgRet.logList[len]
        net.id = 0
        net.name = v.name
        net.zhandouli = v.zhandouli
        net.diff = v.diff
        net.result = v.result
        net.time = v.upTime
        local formationConfig = CombatPosLogic.getFormationConfig(v.formation)
        net.formation = formationConfig.name
        net.videoIndex = v.videoIndex
        fontHeroList(net.list,v.target)
    end
    msgRet.logList[0] = len
    --Msg.trace(msgRet)
    Msg.send(msgRet,human.fd)
end

function CGVideo(human, videoIndex)
    local msgRet = InnerMsg.lw.LW_UNION_WAR_VIDEO
    msgRet.uuid = human.db._id
    msgRet.unionUuid = human.db.unionUuid
    msgRet.index = videoIndex
    InnerMsg.sendMsg(0, msgRet)   
end

function WLVideo(human,msg)
    CombatLogic.repeatCombat(human, msg.combatInfo)
end

--请求：挑战
--返回：挑战失败原因或者战斗帧
function fight(human,args)
    local actState = getState()
    if actState ~= STATE3 then
        return Broadcast.sendErr(human, Lang.UNION_WAR_FIGHT_ERR_END)
    end
    local msgRet =  InnerMsg.lw.LW_UNION_WAR_FIGHT
    msgRet.unionUuid = human.db.unionUuid
    msgRet.attackUuid = human.db._id
    msgRet.defendUuid = args[1]
    msgRet.diff = args[2]
    InnerMsg.sendMsg(0, msgRet)
    print("================fight",   msgRet.diff)
end

function sendfightErr(human, msg)
    if msg.state == UnionWarMiddleLogic.FIGHT2 then
        Broadcast.sendErr(human, Lang.UNION_WAR_FIGHT_ERR_TILI)
    elseif msg.state == UnionWarMiddleLogic.FIGHT3 then  
        Broadcast.sendErr(human, Lang.UNION_WAR_FIGHT_ERR_ING)
    elseif msg.state == UnionWarMiddleLogic.FIGHT4 then  
        Broadcast.sendErr(human, Lang.UNION_WAR_FIGHT_ERR_BEING)
    elseif msg.state == UnionWarMiddleLogic.FIGHT5 then  
        Broadcast.sendErr(human, Lang.UNION_WAR_FIGHT_ERR_STAR)
    elseif msg.state == UnionWarMiddleLogic.FIGHT6 then  
        Broadcast.sendErr(human, Lang.UNION_WAR_FIGHT_ERR_ZIGE)
    end
end

function WLFight(human,msg)
    print("================wlfight",msg.state,UnionWarMiddleLogic.FIGHT1)
    if msg.state ~= UnionWarMiddleLogic.FIGHT1 then
        sendfightErr(human, msg)      
        return 
    end
    human.unionWar = {}
    human.unionWar.target = Util.copyTable(msg.defender)
    human.unionWar.diff = msg.diff
    human.unionWar.name = msg.name
    CombatLogic.combatBegin(human,1001, {}, CombatDefine.COMBAT_TYPE12)
end

function getCombatObjList(human, side)
    if side == CombatDefine.ATTACK_SIDE then
        return CombatLogic.getHumanObjList(human,CombatDefine.COMBAT_TYPE1)
    else
        local target = human.unionWar.target
        local diff = human.unionWar.diff
        local rate = RobotExcel[target.index].rate[diff]
        for k,v in pairs(target.objList) do
            v.attrs[RoleDefine.ATK] = v.attrs[RoleDefine.ATK] * rate/10000
            v.attrs[RoleDefine.DEF] = v.attrs[RoleDefine.DEF] * rate/10000
            v.attrs[RoleDefine.HP] = v.attrs[RoleDefine.HP] * rate/10000
        end
        return target.objList, target.helpList, target.rolebase,target.formation, target.jiban
    end
end

--挑战结束回调
function onFightEnd(human,ret, combatType, cbParam, combatInfo)
    local msgRet = InnerMsg.lw.LW_UNION_WAR_FIGHT_END
    msgRet.upTime = os.time()
    msgRet.uuid = human.db._id
    msgRet.unionUuid = human.db.unionUuid
    msgRet.combatInfo = combatInfo
    InnerMsg.sendMsg(0, msgRet)
    combatInfo.endStatus = CombatLogic.COMBAT_END_STATUS1
    human.unionWar =  human.unionWar or {}
    human.unionWar.combatInfo = combatInfo
end

function WLFightEnd(human,msg)
    local msgRet = Msg.gc.GC_UNION_WAR_FIGHT_END
    msgRet.diff = msg.diff
    msgRet.unionStar = msg.unionStar
    msgRet.defendStar = msg.defender.defendStar
    msgRet.defendUuid = msg.defender.uuid or ""
    msgRet.defIndex = msg.defender.index
    msgRet.cnt = msg.cnt

    local combatInfo = msg.combatInfo
    local target = msg.defender
    local diff = msg.diff
    local isFeixu = msg.isFeixu == 1 and true or false
    local robotConf = RobotExcel[target.index]
    local rate,star,jifen = getDiff(robotConf, diff,target.monsterOutID, isFeixu)
    combatInfo.endParam = rate.."|"..star.."|"..msg.defUnionName 
    combatInfo.rewardItem = robotConf.item[diff]
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData = localData[human.db.unionUuid]
    local rankData = unionWarData.rank
    local addStar = msg.addStar
    local memberData = unionWarData.member[human.db._id]
    if combatInfo.isWin then        
        if memberData then
            memberData.cnt = memberData.cnt + 1
            local chengjiuData = getUnionWarData(human,memberData)
            chengjiuData.cnt = chengjiuData.cnt + 1     
        end
    else
        combatInfo.rewardItem = robotConf.item2[diff]
        jifen = 1
        addStar = 0
    end

    if memberData then
        local humanData = getUnionWarData(human,memberData)
        humanData.fightCnt = humanData.fightCnt or 0
        humanData.fightCnt = msg.cnt
        humanData.fightTime = os.time()
    end
   
    
    -- 玩家增加 公会战积分 星级
    for k,v in ipairs(rankData) do
        if v[1] == human.db._id then
            v[2] = v[2] + jifen
            v[3] = v[3] + addStar
            break
        end
    end

    table.sort(rankData,function(a,b)
        return a[2] > b[2]
    end)
    UnionWarDBLogic.updateDB()

    fontSimpleRank(msgRet.threeRank, human.db.unionUuid)
    Msg.send(msgRet,human.fd)
    
    for k,v in ipairs(combatInfo.rewardItem) do
        BagLogic.addItem(human, v[1], v[2], "unionWar")
    end

    CombatLogic.sendCombatFinish(human,combatInfo)
    human.unionWar = nil

    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_1006)
end

-- 通知参与公会战的在线玩家场景更新 星级 同步
function WLFightTongzhi(msg)
    local msgRet = Msg.gc.GC_UNION_WAR_SCENE_INFO
    msgRet.unionUuid = msg.atkUnion
    msgRet.unionStar = msg.atkUnionStar
    msgRet.defendUuid = msg.defUuid
    msgRet.defendStar = msg.defStar
    msgRet.defIndex = msg.defIndex
    msgRet.targetUnion = msg.defUnion
    local ToUuid = msg.unionUuid
    fontSimpleRank(msgRet.threeRank, ToUuid)  
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData = getLocalUnionWarData(localData, ToUuid)
    for uuid,_ in pairs(unionWarData.member) do
        if uuid ~= msg.atkUuid then
            local human = ObjHuman.onlineUuid[uuid]
            if human then
                Msg.send(msgRet,human.fd)
            end
        end
    end
end

--请求：开箱子
--返回：开箱子
function CGBox(human)
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData =  getLocalUnionWarData(localData,human.db.unionUuid)
    local boxData = unionWarData.box
    local msgRet = Msg.gc.GC_UNION_WAR_BOX
    msgRet.leftTime = 0
    msgRet.isWin = 1
    local len = 0
    local now = os.time()
    if boxData and now < boxData.endTime then
        msgRet.leftTime = boxData.endTime - now
        msgRet.isWin = unionWarData.isWin
        for k,v in ipairs(boxData.list) do
            len = len + 1
            local net = msgRet.list[len]
            if v[3] then
                net.isOpen = 1
                net.name = unionWarData.member[v[3]].name
                Grid.makeItem(net.item[1],v[1],v[2])
                net.item[0] = 1

                if net.name == "" then
                    local fake = {}
                    RoleLogic.getRoleBaseByUuid(v[3], fake)
                    net.name = fake and fake.name or ""
                end
            else
                net.isOpen = 2
                net.name = ""
                net.item[0] = 0
            end
        end
    end
    msgRet.list[0] = len
 --   Msg.trace(msgRet)
    Msg.send(msgRet,human.fd)
end

-- 战果宝箱领取
function CGBoxGet(human,ind)
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData =  getLocalUnionWarData(localData,human.db.unionUuid)
    local boxData = unionWarData.box
    if not boxData then
        return
    end
    if not unionWarData.member[human.db._id] then
        return
    end

    local now = os.time()
    if now > boxData.endTime then
        Broadcast.sendErr(human, Lang.UNION_WAR_BOX_TIME_ERR) 
        return 
    end

    if not unionWarData.member[human.db._id].boxTime then
        Broadcast.sendErr(human, Lang.UNION_WAR_BOX_TIME_ERR_2)  
        return 
    end

    if unionWarData.member[human.db._id].boxTime < boxData.endTime then
        Broadcast.sendErr(human, Lang.UNION_WAR_BOX_TIME_ERR_2)  
        return 
    end

    if not boxData.list[ind] then
        return
    end

    if boxData.list[ind][3] then
        Broadcast.sendErr(human, Lang.UNION_WAR_BOX_NOT_ERR) 
        return
    end

    for k,v in ipairs(boxData.list) do
        if v[3] == human.db._id then
            Broadcast.sendErr(human, Lang.UNION_WAR_BOX_GET_ERR)
            return
        end
    end

    boxData.list[ind][3] = human.db._id
    local itemID = boxData.list[ind][1]
    local itemCnt = boxData.list[ind][2]

    BagLogic.cleanMomentItemList()
    BagLogic.updateMomentItem(BagLogic.ADDITEM_TYPE_1, itemID, itemCnt)
    BagLogic.addMomentItemList(human, "unionWar")
    local msgRet = Msg.gc.GC_UNION_WAR_BOX_GET
    msgRet.ind = ind
    local net = msgRet.box
    net.isOpen = 1
    net.name = unionWarData.member[human.db._id].name
    Grid.makeItem(net.item[1],itemID, itemCnt)
    net.item[0] = 1 
    Msg.send(msgRet,human.fd)

    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_1006)
    updateRed(human)
end

-- 公会战结束
function actFinish(msg)
    local localData = UnionWarDBLogic.getLocalData()
    local now = os.time()
    local d = os.date("*t",now)
    d.hour = HOUR4[1]
    d.min = 0
    d.sec = 0
    local endTime = os.time(d) + 24 * 3600
    local boxItem
    local perExp = DefineConf.perExp
    local randMax
    for k,v in ipairs(msg.list) do
        if v[4] == Config.SVR_INDEX then
            local unionWarData = localData[v[1]]
            if unionWarData then
                if v[3] == 1 then
                   boxItem = DefineConf.boxItem
                else
                    boxItem = DefineConf.boxItem2
                end
                randMax = #boxItem
                unionWarData.isWin = v[3]
                unionWarData.star = v[2]
                Util.initTable(unionWarData.box)
                unionWarData.box = {endTime = endTime,list = {}}
                for i = 1,unionWarData.memberCnt do
                    local r = math.random(1,randMax)
                    unionWarData.box.list[i] = {boxItem[r][1],boxItem[r][2]}
                end

                if v[3] == 1 then
                    unionWarData.exp = unionWarData.exp + unionWarData.memberCnt * perExp
                    unionWarData.cnt = unionWarData.cnt + 1        
                    unionWarData.lv = LvExcel[#LvExcel].lv   
                    for k,v in ipairs(LvExcel) do
                        if unionWarData.exp < v.exp then
                            unionWarData.lv = v.lv - 1
                            break
                        end
                    end
                end
            end
        end
    end
    UnionWarDBLogic.updateDB()

    local localData = UnionWarDBLogic.getLocalData()
    local title = MailExcel[MailDefine.MAIL_ID_UNION_WAR].title
    local content = MailExcel[MailDefine.MAIL_ID_UNION_WAR].content
    local senderName = MailExcel[MailDefine.MAIL_ID_UNION_WAR].senderName

    for unionUuid,unionWarData in pairs(localData) do
        for k,v in ipairs(unionWarData.rank) do
            if v[2] == 0 then
                break
            end
            local rankID = getUnionWarRankRewardID(k)
            local conf = RankExcel[rankID]
            if not conf then
                break
            end
            MailManager.add(MailManager.SYSTEM, v[1], title, Util.format(content, k, v[2]) , conf.item, senderName)  
        end
    end
end

--0 不可领取 1 可以领取 2 已经领取
CHENGJIU_STATE0 = 0
CHENGJIU_STATE1 = 1
CHENGJIU_STATE2 = 2
function CGChengjiu(human,type)
    local ChengjiuExcel = getChengjiuExcel(type)
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData = getLocalUnionWarData(localData,human.db.unionUuid)
    local memberData = getLocalMemberData(unionWarData,human.db._id)
    local humanData = getUnionWarData(human,memberData)
    local getList,cnt
    if type == 1 then
        cnt = humanData.cnt
        getList = humanData.chengjiu[1]
    else
        cnt = unionWarData.cnt
        getList = humanData.chengjiu[2]
    end
    local msgRet = Msg.gc.GC_UNION_WAR_CHENGJIU
    msgRet.type = type
    local len = 0
    for k, v in ipairs(ChengjiuExcel) do
        len = len + 1
        local net = msgRet.list[len]
        net.id = k
        net.title = v.title or ""
        net.maxCnt = v.cnt
        net.cnt = cnt
        if getList[k] then
            net.state = CHENGJIU_STATE2
        elseif v.cnt <= cnt then
            net.state = CHENGJIU_STATE1
        else
            net.state = CHENGJIU_STATE0
        end
        local len1 = 0
        for k1,v1 in ipairs(v.item) do
            len1 = len1 + 1
            Grid.makeItem(net.item[len1],v1[1],v1[2])
        end
        net.item[0] = len1
    end
    msgRet.list[0] = len

    Msg.send(msgRet,human.fd)
end

function chegnjiuFinishGm(human, type)
    local ChengjiuExcel = getChengjiuExcel(type)
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData = localData[human.db.unionUuid]
    local memberData = getLocalMemberData(unionWarData,human.db._id)
    if not memberData then
        --未参与公会战
        return
    end
    local humanData = getUnionWarData(human,memberData)
    if type == 1 then
        humanData.cnt =  humanData.cnt or 0 
        humanData.cnt =  humanData.cnt + 10
    else
        unionWarData.cnt = unionWarData.cnt + 10
    end
    UnionWarDBLogic.updateDB()
end

function CGChengjiuGet(human,type,id)
    local ChengjiuExcel = getChengjiuExcel(type)
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData = getLocalUnionWarData(localData,human.db.unionUuid)
    local memberData = getLocalMemberData(unionWarData,human.db._id)
    if not memberData then
        --未参与公会战
        return
    end
    local humanData = getUnionWarData(human,memberData)
    local getList,cnt
    if type == 1 then
        cnt = humanData.cnt
        getList = humanData.chengjiu[1]
    else
        cnt = unionWarData.cnt
        getList = humanData.chengjiu[2]
    end
    if getList[id] then
        --已经领取
        return
    end
    local conf = ChengjiuExcel[id]
    if cnt < conf.cnt then
        --未达成成就
        return
    end

    getList[id] = 1

 --   Util.printTable(conf.item)
    BagLogic.addItemList(human, conf.item, "unionWar")

    local msgRet = Msg.gc.GC_UNION_WAR_CHENGJIU_GET
    msgRet.type = type
    msgRet.id = id
    Msg.send(msgRet,human.fd)

    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_1006)
    updateRed(human)
end


local function getShopExcel(type)
    if type == 1 then
        return UnionWarExcel.shop1
    else
        return UnionWarExcel.shop2
    end
end

function upWarShopLv(human, lv)
    local localData = UnionWarDBLogic.getLocalData() 
    local unionWarData = getLocalUnionWarData(localData,human.db.unionUuid)
    if not unionWarData then return end 
    unionWarData.lv = lv
  
end

function CGShop(human,type)
    local ShopExcel = getShopExcel(type)
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData = getLocalUnionWarData(localData,human.db.unionUuid)
    local memberData = getLocalMemberData(unionWarData,human.db._id)
    local humanData = getUnionWarData(human,memberData)
    local buyList
    if type == 1 then
        buyList = humanData.shop[1]
    else
        buyList = humanData.shop[2]
    end


    local msgRet = Msg.gc.GC_UNION_WAR_SHOP_QUERY
    msgRet.type = type
    local lv = unionWarData.lv
    msgRet.shopLv = lv
    msgRet.exp = unionWarData.exp
    local nextShopConf = LvExcel[unionWarData.lv + 1]
    msgRet.maxExp = nextShopConf and nextShopConf.exp or 0
    local len = 0
    for k,v in pairs(ShopExcel) do
        if v.lv <= lv + 1 then
            len = len + 1
            local net = msgRet.list[len]
            net.id = k
            net.cnt = buyList[k] or 0
            net.maxCnt = v.limit
            net.needLv = v.lv
            Grid.makeItem(net.item,v.item[1],v.item[2])
            net.cost = v.cost
            net.discount = v.discount
        end
        
    end
    msgRet.list[0] = len
    Msg.send(msgRet,human.fd)
end

function CGBuy(human,type,id,buyCnt)
    local ShopExcel = getShopExcel(type)
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData = getLocalUnionWarData(localData,human.db.unionUuid)
    local memberData = getLocalMemberData(unionWarData,human.db._id)
    local humanData = getUnionWarData(human,memberData)
    local buyList
    if type == 1 then
        buyList = humanData.shop[1]
    else
        buyList = humanData.shop[2]
    end

    local conf = ShopExcel[id]

    if conf.lv > unionWarData.lv then
        --等级不够
        return
    end

    buyCnt = buyCnt or 1
    local cnt = buyList[id] or 0

    if conf.limit > 0 and cnt + buyCnt > conf.limit then
        --达到限购次数
        return
    end

    if not ObjHuman.checkRMB(human, conf.cost * buyCnt) then
        return
    end
    cnt = cnt + buyCnt
    buyList[id] = cnt
    ObjHuman.decZuanshi(human, -conf.cost * buyCnt, "unionWar")
    BagLogic.cleanMomentItemList()
    BagLogic.updateMomentItem(BagLogic.ADDITEM_TYPE_1, conf.item[1],conf.item[2] * buyCnt)
    BagLogic.addMomentItemList(human,  "unionWar")

    local msgRet = Msg.gc.GC_UNION_WAR_SHOP_BUY
    msgRet.type = type
    msgRet.id = id
    msgRet.cnt = cnt
    Msg.send(msgRet,human.fd)
    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_1006)

    updateRed(human)
end

function CGRank(human)
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData = getLocalUnionWarData(localData,human.db.unionUuid)
    local memberList = unionWarData.member
    local msgRet = Msg.gc.GC_UNION_WAR_RANK
    local len = 0
    for k,v in ipairs(unionWarData.rank) do
        len = len + 1
        local net = msgRet.list[len]
        net.uuid = v[1]
        net.rank = k
        local member = memberList[v[1]]
        RoleLogic.makeRoleBase(member.rolebase,net.roleBase)
        net.job = member.post
        local rankID = getUnionWarRankRewardID(k)
        local len1 = 0
        for k1,v1 in ipairs(RankExcel[rankID].item) do
            len1 = len1 + 1
            Grid.makeItem(net.items[len1],v1[1],v1[2])
        end
        net.items[0] = len1
        net.jifen = v[2]
        net.star = v[3]            
    end
    msgRet.list[0] = len
    Msg.send(msgRet,human.fd)
end

function auto(str)
    print(" auto   1111")
    local Gm = require("chat.Gm")
    local CreateRole = require("role.CreateRole")
    local memberCnt = 30
    local now = os.time()
    local union = UnionDBLogic.getUnionByName(str)
    local teamUuidStr = ""
    local teamHide = {[0] = memberCnt}
    for i = 1, memberCnt do
        local account = str .. string.format("%02d", i)
        local db = RoleDBLogic.getDbByAccount(account)
        if not db then
            db = CreateRole.creatFakeDb(account)
            db.lastLoginTime = os.time()
            db.lastLogoutTime = os.time() 
        end
        local human = {}
        human.db = db
   --     ObjHuman.exPand(human)
        Gm.d3.god(human)
        if not union then
            union = UnionDBLogic.addUnion(human, str, 1, "")
        end
        if not union then return end
        if not db.unionUuid then
            db.unionUuid = union._id
            UnionDBLogic.addUnionMember(union, human.db._id)
        end
        CombatPosLogic.setCombatByUnionWarGm(human, CombatDefine.COMBAT_TYPE3)
        union.member[human.db._id].lastDonateTime = now
        ObjHuman.save(human)
    end
    union.lv = UNION_LV 
    UnionDBLogic.updateUnionData(union)
end

local UNION_RANKREWARD_STATE = nil
function CGRankReward(human)
    local msgRet = Msg.gc.GC_UNION_WAR_RANK_REWARD
    if not UNION_RANKREWARD_STATE then
        for k, v in ipairs(RankExcel) do
            local net = msgRet.list[k]
            net.id = k
            net.minRank = v.minRank
            net.maxRank = v.maxRank
            for j, h in ipairs(v.item) do
                Grid.makeItem(net.items[j],  h[1], h[2])
            end
            net.items[0] = #v.item
        end
        msgRet.list[0] = #RankExcel
    end
    Msg.send(msgRet, human.fd) 
end


function isDotByBox(human, unionWarData)
    local now = os.time()
    
    if not unionWarData then
        local localData = UnionWarDBLogic.getLocalData()
        unionWarData =  getLocalUnionWarData(localData,human.db.unionUuid)
    end
    if not unionWarData then return end 

    local boxData = unionWarData.box
     if not unionWarData.member[human.db._id] then
        return
    end
    if not boxData or not boxData.endTime then return end 
    if now > boxData.endTime then
        return 
    end

    -- 检测 有没有领过
    for k,v in ipairs(boxData.list) do
        if v[3] == human.db._id then
            return
        end
    end
    return true
end

function isDotByShop(human, unionWarData)
    local memberData = getLocalMemberData(unionWarData,human.db._id)
    local humanData = getUnionWarData(human,memberData)
    local buyList
    for type = 1 , 2 do
        if type == 1 then
            buyList = humanData.shop[1]
        else
            buyList = humanData.shop[2]
        end
        local lv = unionWarData.lv
        local len = 0
        local ShopExcel = getShopExcel(type)
        for k,v in pairs(ShopExcel) do
            if v.lv <= lv and not buyList[k] then
                return true
            end            
        end
    end  
end

function isDotByCnt(human, unionWarData)
    local actState = getState()
    if actState == STATE3 and unionWarData.isMatch and Util.isSameDay(unionWarData.matchTime) then
        local memberData = getLocalMemberData(unionWarData,human.db._id)
        local humanData = getUnionWarData(human,memberData)
        if not humanData.fightCnt then 
            return true
        end
        if Util.isSameDay(humanData.fightTime)  then
            if  humanData.fightCnt and humanData.fightCnt < UnionWarExcel.define[1].cnt then
                return true
            end
        else
            return true
        end
    end
end

function isDotByPiPei(human, unionWarData)
    local memberData = getLocalMemberData(unionWarData,human.db._id)
    local humanData = getUnionWarData(human,memberData)

    local actState = getState()

    if actState >= STATE2 and actState < STATE4 and unionWarData.isMatch then
        if not Util.isSameDay(humanData.pipeiLook) then
            return true
        end
       
    end
end

function isDot(human)
    if not human.db.unionUuid then
        return
    end
    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData =  getLocalUnionWarData(localData,human.db.unionUuid)
    if not unionWarData then return end
    -- 成就
    local memberData = getLocalMemberData(unionWarData,human.db._id)
    if isDotChengjiu(human,localData,unionWarData,memberData,1) or isDotChengjiu(human,localData,unionWarData,memberData,2) then
        return true
    end

    if isDotByBox(human, unionWarData) then
        return true
    end

    if isDotByShop(human, unionWarData) then
        return true
    end

    if isDotByCnt(human, unionWarData) then
        return true
    end

    if isDotByPiPei(human, unionWarData) then
        return true
    end
end


-- 更新界面 红点
function updateRed(human)
    local msgRet = Msg.gc.GC_UNION_WAR_RED
    msgRet.cjDot = 0
    msgRet.zgDot = 0
    msgRet.shopDot = 0
    msgRet.fightDot = 0
    msgRet.pipeiDot = 0

    local localData = UnionWarDBLogic.getLocalData()
    local unionWarData =  getLocalUnionWarData(localData,human.db.unionUuid)
    local memberData = getLocalMemberData(unionWarData,human.db._id)

    if not memberData then 
        Msg.send(msgRet,human.fd)
        return 
    end

    if unionWarData and memberData and isDotChengjiu(human,localData,unionWarData,memberData,1) or isDotChengjiu(human,localData,unionWarData,memberData,2) then
        msgRet.cjDot = 1
    end

    if unionWarData and isDotByBox(human, unionWarData) then
        msgRet.zgDot = 1
    end

    if unionWarData and isDotByShop(human, unionWarData) then
        msgRet.shopDot = 1
    end

    if unionWarData and isDotByCnt(human, unionWarData) then
        msgRet.fightDot = 1
    end

    if unionWarData and isDotByPiPei(human, unionWarData) then
        msgRet.pipeiDot = 1
    end

    Msg.send(msgRet,human.fd)
end